package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.*;
import com.stlm2.util.Convert;
import com.stlm2.util.StringUtils;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.dao.ActivityDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("activityService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class ActivityService extends BaseServiceImpl<Activity> {

	@Resource
	private ActivityDao activityDao;
	@Resource
	private UserDao userDao;

	@Override
	protected BaseDao <Activity> getDao() {
		return activityDao;
	}


	public String search(String token, String name,String label,String activityState,String pageNu){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int pageNo=1;
		if(!NumberUtils.isDigits(pageNu)){
			return CodeContent.getModelByCode(0,"未传入查询页数",null);
		}
		pageNo=NumberUtils.toInt(pageNu);

		Activity activity=new Activity();

		if(!StringUtils.isNullOrEmpty(name)){
			activity.setName(name);
		}
		if(NumberUtils.isDigits(activityState)){
			if(NumberUtils.toInt(activityState)==1){
				activity.setActivityState(true);
			}
			if(NumberUtils.toInt(activityState)==0){
				activity.setActivityState(false);
			}
		}
		if (StringUtils.isNotNullAndEmpty(label)){
			activity.setLabel(label);
		}

		ModelMap model=new ModelMap();
		PageView pageview=activityDao.queryPageView(pageNo, 20,activity);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();


	}

	public List<ModelMap> convertCrmList(List<Activity> activityList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (activityList != null &&activityList.size() > 0) {
			for (Activity activity : activityList) {
				ModelMap map = buildModelCrmList(activity);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCrmList(Activity activity) {
		ModelMap model = new ModelMap();
		model.put("id", activity.getId());
		model.put("activityState",activity.getActivityState()?"有效":"无效");
		model.put("activityStateValue",activity.getActivityState()?1:0);
		model.put("name",activity.getName());
		model.put("label",activity.getLabel());
		model.put("remark",activity.getRemark());
		model.put("startTime",Convert.toFullYMDHMS(activity.getStartTime()));
		model.put("endTime",Convert.toFullYMDHMS(activity.getEndTime()));
        model.put("createTime", Convert.toFullYMDHMS(activity.getCreateTime()));
		return  model;
	}


	/** 编辑 使无效
	 * ffl
	 * 2017-12-28 13:50:47
	 * @param token
	 * @param id
	 * @return
	 */
	public String invalid(String token, String id){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}

		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入正确的活动id",null);
		}
		Activity activity=activityDao.getById(NumberUtils.toInt(id));
        if(activity==null){
			return CodeContent.getModelByCode(0,"未找到活动记录",null);
		}
		if(activity.getActivityState()) {
			activity.setActivityState(false);
			activityDao.modify(activity);
			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				jedis.set("seckill:companyCode:"+user.getCompanyCode(),"start:"+activity.getStartTime().getTime()+":end:"+activity.getEndTime().getTime()+":state:"+0);
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				pool.returnResource(jedis);
			}
		}
		return  CodeContent.getModelByCode(1,"",null);


	}

	/** 编辑 使有效
	 * ffl
	 * 2017-12-28 13:50:47
	 * @param token
	 * @param id
	 * @return
	 */
	public String effective(String token, String id){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}

		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入正确的活动id",null);
		}
		Activity activity=activityDao.getById(NumberUtils.toInt(id));
		if(activity==null){
			return CodeContent.getModelByCode(0,"未找到活动记录",null);
		}
		if(!activity.getActivityState()) {
			activity.setActivityState(true);
			activityDao.modify(activity);
			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				jedis.set("seckill:companyCode:"+user.getCompanyCode(),"start:"+activity.getStartTime().getTime()+":end:"+activity.getEndTime().getTime()+":state:"+1);
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				pool.returnResource(jedis);
			}
		}
		return  CodeContent.getModelByCode(1,"",null);


	}

	/**
	 *  活动详情
	 * ffl
	 * 2017-12-28 14:10:38
	 * @param id
	 * @return
	 */
	public String detail( String id){
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入正确的活动id",null);
		}
		Activity activity=activityDao.getById(NumberUtils.toInt(id));
		if(activity==null){
			return CodeContent.getModelByCode(0,"未找到活动记录",null);
		}
		return  CodeContent.getModelByCode(1,"",buildModelCrmList(activity));

	}

	/** 编辑 活动 时间
	 * ffl
	 * 2017-12-28 15:05:36
	 * @param token
	 * @param id
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public String edit(String token, String id,String startTime,String endTime){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}

		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入正确的活动id",null);
		}
		if(StringUtils.isNullOrEmpty(startTime)){
			return CodeContent.getModelByCode(0,"未传入活动开始时间",null);
		}
		if(StringUtils.isNullOrEmpty(endTime)){
			return CodeContent.getModelByCode(0,"未传入活动结束时间",null);
		}
		Activity activity=activityDao.getById(NumberUtils.toInt(id));
		if(activity==null){
			return CodeContent.getModelByCode(0,"未找到活动记录",null);
		}

		Date startTime2=null;
		Date endTime2=null;
		try {
			startTime2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(startTime);
			endTime2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(endTime);

		} catch (Exception e) {
			System.out.println("无法解析开始时间："+startTime+"======结束时间"+endTime );
		}
		activity.setStartTime(startTime2);
		activity.setEndTime(endTime2);
		activityDao.modify(activity);
        int state=0;
        if(activity.getActivityState()){
        	state=1;
		}

		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			jedis.set("seckill:companyCode:"+user.getCompanyCode(),"start:"+startTime2.getTime()+":end:"+endTime2.getTime()+":state:"+state);
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
		return  CodeContent.getModelByCode(1,"",null);


	}


	/** 秒杀活动状态
	 * ffl
	 * 2017-12-28 16:22:01
	 * @param companyCode
	 * @return
	 */
	public String getSeckillActivityRedis(String companyCode){
		int code=1;
		if(NumberUtils.isDigits(companyCode)){
			code=NumberUtils.toInt(companyCode);
		}
		ModelMap model =new ModelMap();
		long current=new Date().getTime();
		Boolean seckillState=false;
		int state=0;
		if(code>0) {
			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				String seckillActivity=jedis.get("seckill:companyCode:" + code);
				if(seckillActivity!=null&& seckillActivity.split(":").length==6){
					String[] seckillStr=seckillActivity.split(":");
					long startTime=Long.valueOf(seckillStr[1]);
					long endTime=Long.valueOf(seckillStr[3]);
					state=Integer.valueOf(seckillStr[5]);
					if(state==1&&startTime<current&&endTime>current){
						seckillState=true;
					}
				}else {//redis 未存入 秒杀活动信息 数据库 查询 并存入redis
					Activity activity=activityDao.getByLabel("seconds_kill");
					if(activity!=null){
						if(activity.getActivityState()){
							state=1;
						}
						long startTime=activity.getStartTime().getTime();
						long endTime=activity.getEndTime().getTime();
						jedis.set("seckill:companyCode:" + code, "start:" + startTime + ":end:" + endTime + ":state:" + state);
						if(state==1&&startTime<current&&endTime>current){
							seckillState=true;
						}
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pool.returnResource(jedis);
			}
		}else {
			return CodeContent.getModelByCode(0,"公司编号错误",null);
		}
		model.put("seckillState",seckillState);
		return CodeContent.getModelByCode(1,"",model);
	}


	/** 秒杀活动状态
	 * ffl
	 * 2017-12-28 16:22:01
	 * @param companyCode
	 * @return
	 */
	public Boolean SeckillActivityState(String companyCode){
		int code=1;
		if(NumberUtils.isDigits(companyCode)){
			code=NumberUtils.toInt(companyCode);
		}
		long current=new Date().getTime();
		Boolean seckillState=false;
		int state=0;
		if(code>0) {
			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				String seckillActivity=jedis.get("seckill:companyCode:" + code);
				if(seckillActivity!=null&& seckillActivity.split(":").length==6){
					String[] seckillStr=seckillActivity.split(":");
					long startTime=Long.valueOf(seckillStr[1]);
					long endTime=Long.valueOf(seckillStr[3]);
					state=Integer.valueOf(seckillStr[5]);
					if(state==1&&startTime<current&&endTime>current){
						seckillState=true;
					}
				}else {//redis 未存入 秒杀活动信息 数据库 查询 并存入redis
					Activity activity=activityDao.getByLabel("seconds_kill");
					if(activity!=null){
						if(activity.getActivityState()){
							state=1;
						}
						long startTime=activity.getStartTime().getTime();
						long endTime=activity.getEndTime().getTime();
						jedis.set("seckill:companyCode:" + code, "start:" + startTime + ":end:" + endTime + ":state:" + state);
						if(state==1&&startTime<current&&endTime>current){
							seckillState=true;
						}
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pool.returnResource(jedis);
			}
		}

		return seckillState;
	}

}